package com.songshuai.customer.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.customer.client.dto.request.sop.DynamicSopListReqDto;
import com.songshuai.customer.client.dto.request.sop.SopListReqDto;
import com.songshuai.customer.client.dto.response.sop.DynamicSopListResDto;
import com.songshuai.customer.client.dto.response.sop.SopListResDto;
import com.songshuai.customer.client.service.SopService;
import com.songshuai.webapi.baseapi.constant.miniprogram.CacheKeys;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.enumerations.sales.redis.RedisExpire;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.PageUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.common.redis.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author:wbl
 * @Date: 2019/3/14
 */
@Slf4j
@Api("Sop")
@RestController
@RequestMapping("/api/cust/sop/")
public class SopController extends BaseController {

    @Autowired
    private SopService sopService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "根据分类获取SOP内容")
    @PostMapping("getSopListByType")
    public CompletableFuture<QueryResponse<SopListResDto>> getSopListByType(@RequestBody BaseParmDto<SopListReqDto> parm,@RequestHeader("token") String token){
        //String currentUserId = this.getCurrentcustomerId();
        String currentUserId = "1";
        return CompletableFuture.supplyAsync(() ->{
            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }

            try {
                PageUtil page = getSyncSopRedis(parm);
                if (page == null) {
                    page = sopService.getSopListByType(parm);
                    setSyncSopRedis(parm,page);
                }
                List<SopListResDto> resList = (List<SopListResDto>) page.getLists();
                return QueryPageRes.setQueryResponseData(resList, page.getTotalSize() == null ? 0L : page.getTotalSize().longValue());
            } catch (Exception e) {
                log.error("api/cust/sop/getSopListByType", e);
                return new QueryResponse(ResultStatus.FAILOfficial.getErrorCode(),e.getMessage());
            }
        });
    }

    @ApiOperation(value = "获取动态SOP内容")
    @PostMapping("getDynamicSopList")
    public CompletableFuture<QueryResponse<DynamicSopListResDto>> getDynamicSopList(@RequestBody BaseParmDto<DynamicSopListReqDto> parm, @RequestHeader("token") String token){
        //String currentUserId = this.getCurrentcustomerId();
        String currentUserId = "1";
        return CompletableFuture.supplyAsync(() ->{
            if(null == currentUserId){
                return new QueryResponse(ResultStatus.FAIL.getErrorCode(),ResultStatus.FAIL.getErrorMsg());
            }
            parm.getParam().setCurrentUserId(currentUserId);
            PageUtil page = getSyncDynamicSopRedis(parm);
            if(page == null) {
                page = sopService.getDynamicSopList(parm);
                setSyncDynamicSopRedis(parm,page);
            }
            List<DynamicSopListResDto> resList = (List<DynamicSopListResDto>) page.getLists();
            return QueryPageRes.setQueryResponseData(resList, page.getTotalSize() == null ? 0L : page.getTotalSize().longValue());
        });
    }

    //提取客户端sop列表缓存
    public PageUtil getSyncSopRedis(BaseParmDto<SopListReqDto> request){
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String subType = request.getParam().getSubType();
        subType = StringUtils.isBlank(subType) == true? "0": subType;
        String redisKey = pageIndex + "_" + pageSize + "_" + subType;
        try {
            Object obj = redisUtil.hget(CacheKeys.CUST_SOP_INFO, redisKey);
            PageUtil page = JSON.parseObject((String)obj,PageUtil.class);
            log.info("get cache:{}",redisKey);
            return page;
        }catch (Exception e){
            log.error("api/cust/sop/getSopListByType", e);
            return null;
        }
    }

    //客户端sop列表缓存
    @Async
    public void setSyncSopRedis(BaseParmDto<SopListReqDto> request, PageUtil page){

        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String subType = request.getParam().getSubType();
        subType = StringUtils.isBlank(subType) == true? "0": subType;
        String redisKey = pageIndex + "_" + pageSize + "_" + subType;
        try {
            JSONObject obj = (JSONObject) JSON.toJSON(page);
            redisUtil.hset(CacheKeys.CUST_SOP_INFO, redisKey, obj.toJSONString(), RedisExpire.TenMinutes.getCode());
            log.info("set cache:{}",redisKey);
        }catch (Exception e){
            log.error("api/cust/sop/getSopListByType", e);
        }
    }

    //提取客户端动态sop列表缓存
    public PageUtil getSyncDynamicSopRedis(BaseParmDto<DynamicSopListReqDto> request){
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String currentUserId = request.getParam().getCurrentUserId();
        String redisKey = pageIndex + "_" + pageSize + "_" + currentUserId;
        try {
            Object obj = redisUtil.hget(CacheKeys.CUST_DYNAMIC_SOP_INFO, redisKey);
            PageUtil page = JSON.parseObject((String)obj,PageUtil.class);
            log.info("get cache:{}",redisKey);
            return page;
        }catch (Exception e){
            log.error("api/cust/sop/getDynamicSopList", e);
            return null;
        }
    }

    //客户端动态sop列表缓存
    @Async
    public void setSyncDynamicSopRedis(BaseParmDto<DynamicSopListReqDto> request, PageUtil page){

        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String currentUserId = request.getParam().getCurrentUserId();
        String redisKey = pageIndex + "_" + pageSize + "_" + currentUserId;
        try {
            JSONObject obj = (JSONObject) JSON.toJSON(page);
            redisUtil.hset(CacheKeys.CUST_DYNAMIC_SOP_INFO, redisKey, obj.toJSONString(), RedisExpire.TenMinutes.getCode());
            log.info("set cache:{}",redisKey);
        }catch (Exception e){
            log.error("api/cust/sop/getDynamicSopList", e);
        }
    }
}
